<template>
  <div ref="editorContainer" class="quill-editor"></div>
</template>

<script>
import { ref, onMounted, onBeforeUnmount, watch } from 'vue';
import Quill from 'quill';
import 'quill/dist/quill.snow.css';

export default {
  props: {
    modelValue: String
  },
  setup(props, { emit }) {
    const editorContainer = ref(null);
    let quill = null;

    const initializeEditor = () => {
      // 创建专用容器
      const container = document.createElement('div');
      editorContainer.value.appendChild(container);

      quill = new Quill(container, {
        theme: 'snow',
        modules: {
          toolbar: [
            [{ header: [1, 2, false] }],
            ['bold', 'italic', 'underline'],
            [{ color: [] }, { background: [] }],
            [{ list: 'ordered' }, { list: 'bullet' }],
            ['blockquote'],
            ['link', 'image'],
            ['clean']
          ]
        }
      });

      quill.on('text-change', () => {
        emit('update:modelValue', quill.root.innerHTML);
      });

      quill.root.innerHTML = props.modelValue;
    };

    const destroyEditor = () => {
      if (quill) {
        // 移除工具栏
        const toolbar = editorContainer.value.querySelector('.ql-toolbar');
        toolbar?.parentNode?.removeChild(toolbar);
        
        // 移除容器内容
        editorContainer.value.innerHTML = '';
        quill = null;
      }
    };

    onMounted(initializeEditor);

    onBeforeUnmount(() => {
      // 清除全局样式
      document.querySelectorAll('.ql-snow, .ql-bubble').forEach(style => {
        style.parentNode?.removeChild(style);
      });
      // 清除工具提示
      document.querySelectorAll('.ql-tooltip').forEach(tip => {
        tip.parentNode?.removeChild(tip);
      });
      destroyEditor();
    });

    watch(() => props.modelValue, (newVal) => {
      if (quill && quill.root.innerHTML !== newVal) {
        quill.root.innerHTML = newVal;
      }
    });

    return { editorContainer };
  }
};
</script>

<style scoped>
.quill-editor {
  height: 200px;
}

/* 深度选择器确保样式作用域 */
.quill-editor >>> .ql-toolbar {
  border-radius: 4px 4px 0 0;
  background: #f5f5f5;
}

.quill-editor >>> .ql-container {
  border-radius: 0 0 4px 4px;
  height: calc(100% - 42px);
}
</style>